package com.itheima.service.iml;

import com.itheima.bean.Category;
import com.itheima.bean.PageBean;
import com.itheima.common.R;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.DishDao;
import com.itheima.exception.CustomException;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tang
 * @date 2022/11/22 20:02
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishDao dishDao;

    @Override
    public R<String> add(Category category) {
        //根据name查询统计,如果大于1抛出异常 分类名称重复

        //根究sort查询统计,如果大于1抛出异常 排序名称重复
        Integer index = categoryDao.add(category);
        if (index > 0) {
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @Override
    public R<PageBean<Category>> findPage(Integer page, Integer pageSize) {
        //计算页码
        page = (page - 1) * pageSize;
        //查询分页数据
        List<Category> pageList = categoryDao.findPage(page, pageSize);
        //查询分页总记录数
        Integer count = categoryDao.findCount(page, pageSize);
        //封装数据到PageBean<Employee>
        PageBean<Category> pageBean = new PageBean<>(pageList, count);

        return R.success(pageBean);
    }

    @Override
    public R<String> deleteById(Long id) {
        //1.判断分类id是否绑定有菜品 没有则删除
        //1.1根据分类id查询dish表
        Integer count = dishDao.selectByCategoryId(id);
        if (count > 0) {
            throw new CustomException("当前分类绑定有菜品");
        }

        Integer count1 = categoryDao.deleteById(id);
        if (count1 > 0) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @Override
    public R<String> updateById(Category category) {
        categoryDao.updateById(category);
        return R.success("修改成功");
    }

    @Override
    public R<List<Category>> findByType(Integer type) {
        List<Category> categorys = categoryDao.findByType(type);
        if (categorys == null) {
            throw new CustomException("查询分类失败");
        }

        return R.success(categorys);
    }


}
